import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
// import { useUserStore } from '@/store/user'
import { useStore } from "vuex";
// 路由组件导入
const HomeView = () => import('../views/HomeView.vue')
const UserView = () => import('../views/UserView.vue')
const RoleView = () => import('@/views/RoleView.vue')
const PermissView = () => import('@/views/PermissView.vue')
const LoginView = () => import('../views/LoginView.vue')
const NotFoundView = () => import('../views/NotFound.vue')


// 静态路由
const staticRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView,
    meta: {
      // roles: ['admin', 'accountA', 'accountB'], // 修正为数组格式
      isMenu: false,
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFoundView,
    meta: {
      // roles: ['admin', 'accountA', 'accountB'], // 修正为数组格式
      isMenu: false,
    }
  }
];

// 动态路由
 const dynamicRoutes = [
  {
    path: '/admin',
    name: 'admin',
    component: HomeView,
    meta: {
      title: "首页",
      title_path: '/admin',
      isMenu: false,
      sub_title: "后台管理",
      roles: ['admin', 'accountA', 'accountB'] // 修正为数组格式
    },
    children: [
      {
        path: '/admin/user',
        name: 'user',
        component: UserView,
        meta: {
          title: "用户管理",
          title_path: '/admin/user',
          icon: "AppstoreOutlined", // 方便生成动态菜单,注意：统一双引号
          isMenu: true,
          sub_title: "用户信息编辑",
          roles: ['admin', 'accountA', 'accountB'] // 修正为数组格式
        }
      },
      {
        path: '/admin/role',
        name: 'role',
        component: RoleView,
        meta: {
          title: "角色管理",
          title_path: '/admin/role',
          icon: "InboxOutlined",
          isMenu: true,
          sub_title: "角色信息编辑",
          roles: ['admin', 'accountA','accountB'] // 修正为数组格式
        }
      },
      {
        path: '/admin/permis',
        name: 'permis',
        component: PermissView,
        meta: {
          title: "权限管理",
          title_path: '/admin/permis',
          icon: "DesktopOutlined",
          isMenu: true,
          sub_title: "权限信息编辑",
          roles: ['admin', 'accountA'] // 修正为数组格式
        }
      }
    ]
  }
]

const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHistory(process.env.BASE_URL),
  routes: staticRoutes
})

// 根据角色筛选出路由
 function filterRoutesByRole(routes: any[], userRoles: string[]): any[] {
  return routes
    .map((route) => {
      // 复制路由对象避免修改原始数据
      const filteredRoute = { ...route };

      // 处理子路由（递归）
      if (route.children && route.children.length > 0) {
        filteredRoute.children = filterRoutesByRole(route.children, userRoles);
      }

      return filteredRoute;
    })
    .filter((route) => {
      // 过滤条件：无权限要求 或 有权限且用户有权限
      return (
        !route.meta?.roles ||
        route.meta.roles.some((role: string) => userRoles.includes(role))
      );
    });
}

// 根据路由动态创建菜单
export function generateDynamicRoutes() {
  const userRoles = localStorage.getItem("role_code")?[localStorage.getItem("role_code")]:[]
  console.log(userRoles);
  const accessibleRoutes = filterRoutesByRole(dynamicRoutes, userRoles);

  // 先移除可能已存在的动态路由
  router.getRoutes().forEach((r) => {
    if (dynamicRoutes.some((dr) => dr.name === r.name)) {
      router.removeRoute(r.name!);
    }
  });

  // 添加新路由
  accessibleRoutes.forEach((route) => {
    console.log("route>>>>>>>>>>", route);
    // const parent_path = route.path
    router.addRoute(route);
    // if (route.children && route.children.length > 0) {
    //   route.children.map((route: any) => {
    //     const itemroute = {
    //       ...route,
    //       path:route.meta.title_path,
    //     }
    //     console.log("route>>>>>>>>>>", itemroute);
    //     router.addRoute(itemroute);
    //   });
    // }
  });
  console.log("accessibleRoutes>>>>>>>>>", accessibleRoutes);
  // 4. 确保添加404路由（关键！）
  // router.addRoute({
  //   path: "/:pathMatch(.*)*",
  //   name: "NotFound",
  //   component: () => import("@/views/NotFound.vue"),
  // });
}

// 每次加载调用一次，根据角色生成对应的路由
generateDynamicRoutes()

// 导航守卫
router.beforeEach((to, from, next) => {
  const store = useStore();
  const userRoles = to.meta.roles || [];
  console.log(store.state.roles,dynamicRoutes,dynamicRoutes[0])

  // 如果路由需要权限验证
  if (to.meta.roles) {
    // const hasPermission = to.meta.roles.some(role => userStore.roles.includes(role));
    const hasPermission = userRoles.some((role: any) => store.state.roles.includes(role));

    // const hasPermission = to.meta.roles.includes(store.roles);
    if (!hasPermission) {
      return next({ name: 'NotFound' }); // 无权限时跳转到 404 页面
    }
  }
  next(); // 允许访问
});

export default router